package com.szsfm.vehiclemanagement.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.os.Bundle;
import android.os.Environment;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.ImageView;

import com.szsfm.vehiclemanagement.R;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;


public class CameraActivity extends Activity implements SurfaceHolder.Callback {

    private SurfaceView surfaceView;
    private ImageView imageView;
    private Camera camera;
    private Camera.Parameters parameters;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera);
        surfaceView = (SurfaceView) findViewById(R.id.surfaceView);
        surfaceView.getHolder().addCallback(this);
        surfaceView.getHolder().setKeepScreenOn(true);
        surfaceView.getHolder().setFixedSize(720, 1280);
        surfaceView.getHolder().setFormat(PixelFormat.RGB_888);
        imageView = (ImageView) findViewById(R.id.imgCam);
        imageView.setOnClickListener(new OnCam());
    }

    class OnCam implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            if (camera != null) {
                camera.takePicture(null, null, new OnPicture()); // 拍照
            }
        }
    }

    class OnPicture implements Camera.PictureCallback {
        @Override
        public void onPictureTaken(byte[] data, Camera camera) {
            try {
                saveToSDCard(data); // 保存图片到sd卡中
                camera.startPreview(); // 拍完照后，重新开始预览
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 将拍下来的照片存放在SD卡中
     */
    public void saveToSDCard(byte[] data) throws IOException {
        long date = System.currentTimeMillis();
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss"); // 格式化时间
        String filename = format.format(date) + ".jpg";
        File fileFolder = new File(Environment.getExternalStorageDirectory()
                + "/vehiclemanager/");
        String path = Environment.getExternalStorageDirectory()
                + "/vehiclemanager/" + filename;
        if (!fileFolder.exists()) { // 如果目录不存在，则创建一个名为"finger"的目录
            fileFolder.mkdir();
        }
        File jpgFile = new File(fileFolder, filename);
        FileOutputStream outputStream = new FileOutputStream(jpgFile); // 文件输出流
        outputStream.write(data); // 写入sd卡中
        outputStream.close(); // 关闭输出流
        Intent intent = new Intent(CameraActivity.this, MainActivity.class);
        intent.putExtra("Path", path);
        setResult(RESULT_OK, intent);
        finish();
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        parameters.setPictureSize(width, height);
        parameters.setPreviewSize(720, 1280); // 设置预览大小
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (OpenCam()) {
            parameters = camera.getParameters();
            parameters.setPictureFormat(PixelFormat.JPEG);
            //   parameters.setFlashMode(Camera.Parameters.FLASH_MODE_AUTO);
            parameters.setJpegQuality(100); // 设置照片质量
            parameters.set("rotation", 90);
            camera.setParameters(parameters);
            try {
                camera.setDisplayOrientation(getPreviewDegree(CameraActivity.this));
                camera.cancelAutoFocus();
                camera.setPreviewDisplay(holder);
                camera.startPreview();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        if (camera != null) {
            camera.stopPreview();
            camera.setPreviewCallback(null);
            camera.release();
            camera = null;
        }
    }

    //获得屏幕方向
    public static int getPreviewDegree(Activity activity) {
        int rotation = activity.getWindowManager().getDefaultDisplay()
                .getRotation();
        int degree = 0;
        switch (rotation) {
            case Surface.ROTATION_0:
                degree = 90;
                break;
            case Surface.ROTATION_90:
                degree = 0;
                break;
            case Surface.ROTATION_180:
                degree = 270;
                break;
            case Surface.ROTATION_270:
                degree = 180;
                break;
        }
        return degree;
    }

    public boolean OpenCam() {
        if (camera == null) {
            try {
                camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK);//打开后置摄像头
            } catch (Exception e) {
                return false;
            }
        }
        return true;
    }
}
